<template>
  <e-container :loading="loading">
    <e-title :title="action === 'edit' ? 'Edit Contact' : 'Add Contact'" />
    <a-divider />
    <div class="form">
      <a-form ref="formInstance" :model="apiData" layout="vertical" :rules="rules">
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Name" name="departmentName">
              <a-input v-model:value="apiData.departmentName" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="E-mail" name="email">
              <a-input v-model:value="apiData.email" @blur="() => (apiData.email = apiData.email.trim())" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="Note" name="note">
              <a-input v-model:value="apiData.note" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-divider />
    <div class="buttons">
      <a-space size="middle">
        <a-button @click="handleContactCancel">Cancel</a-button>
        <a-button
          v-permission="action === 'edit' ? 'Contact:Edit' : 'Contact:Add'"
          type="primary"
          @click="handleContactSave"
          >Save</a-button
        >
      </a-space>
    </div>
  </e-container>
</template>

<script setup>
import { inject, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import EContainer from '@/components/EContainer.vue'
import ETitle from '@/components/ETitle.vue'
import Contact from '@/api/client/contact.js'
import {
  CHECK_FORM_INTEGRITY,
  CONFIRM_BACK_TO_DETAIL,
  CONTACT_CREATED_SUCCESS,
  CONTACT_UPDATE_SUCCESS
} from '@/constants/message.js'
const { Modal, message } = inject('Feedback')

const props = defineProps({
  referenced: {
    type: Boolean,
    default: false
  },
  params: {
    type: Object,
    default() {
      return {}
    }
  }
})
const route = useRoute()
const router = useRouter()
const loading = ref(true)
const gutter = [120, 16]
// 组件被外部引用则通过道具取参数，正常通过路由取参数
const { id, action, contactId } = props.referenced ? props.params : route.params
const formInstance = ref(null)
const rules = {
  departmentName: [
    {
      required: true,
      whitespace: true,
      message: 'Please input Name',
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      whitespace: true,
      message: 'Please input E-mail',
      trigger: 'blur'
    },
    {
      type: 'email',
      message: 'Incorrect email address format',
      trigger: 'blur'
    },
    {
      validator: (rule, value) => {
        const regex = /@(ecinnovations)\./g
        return regex.test(value) ? Promise.reject(new Error()) : Promise.resolve()
      },
      message: 'Incorrect email suffix',
      trigger: 'blur'
    }
  ]
}
const apiData = reactive({
  departmentName: '',
  email: '',
  note: ''
})
if (action === 'edit') {
  /*
  new Promise(resolve => {
    useContactInfo(contactId, resolve, true)
  }).then(contactInfo => {
    loading.value = false
    Object.keys(apiData).forEach(key => {
      apiData[key] = contactInfo.raw.value[key]
    })
  })
   */
  Contact.detailDepartment(contactId)
    .then(({ data }) => {
      apiData.id = data.id
      apiData.email = data.email
      apiData.departmentName = data.departmentName
      apiData.note = data.note
    })
    .finally(() => {
      loading.value = false
    })
}
if (action === 'create') {
  loading.value = false
  document.title = 'Add Contact'
}
const emits = defineEmits(['cancel', 'updated'])
const handleContactCancel = () => {
  Modal.confirm({
    content: CONFIRM_BACK_TO_DETAIL,
    okButtonProps: { danger: true },
    onOk: () => {
      props.referenced ? emits('cancel') : router.back()
    }
  })
}
const handleContactSave = () => {
  formInstance.value
    .validate()
    .then(() => {
      loading.value = true
      if (action === 'edit') {
        apiData.clientOrgID = id
        Contact.updateDepartmentContact(apiData)
          .then(() => {
            message.success(CONTACT_UPDATE_SUCCESS)
            emits('updated')
            if (window.location.hash === '#auto-close') window.close()
            if (!props.referenced) router.back()
          })
          .finally(() => {
            loading.value = false
          })
      }
      if (action === 'create') {
        apiData.clientOrgID = id
        Contact.addDepartmentContact(apiData)
          .then(() => {
            message.success(CONTACT_CREATED_SUCCESS)
            emits('updated')
            if (!props.referenced) router.back()
          })
          .finally(() => {
            loading.value = false
          })
      }
    })
    .catch(() => {
      message.error(CHECK_FORM_INTEGRITY)
    })
}
</script>

<style lang="less" scoped>
.form {
  padding: 0 228px;
}
.buttons {
  text-align: center;
}
</style>
<route lang="yaml">
name: Department Contact Edit
path: '/client/:id/department-contact/:action/:contactId?'
meta:
  sort: 1
  title: Contact Edit
  permission: Contact
</route>
